package com.hxc.interceptor;

import com.hxc.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1 获取url
        String requestURI = request.getRequestURI();
        log.info("拦截请求路径:{}", requestURI);
        // 2 判断请求url中是否包含login（可以通过注册时排除，无需再进行判）
        // 3 获取令牌
        String token = request.getHeader("token");
        // 4 判断令牌是否存在，如果不存在返回401
        if (token == null) {
            log.warn("令牌不存在");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            // 不放行
            return false;
        }
        // 解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("解析token：{}",claims);
        } catch (Exception e) {
            log.info("令牌解析失败：{}",e.getMessage());
            // e.printStackTrace();
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            // 不放行
            return false;
        }
        return true;
    }
}
